package tree;

public class ZuiJinGongGongZhuXian {
    //二叉树节点类
    static class Node{
        int value;
        Node left;
        Node right;
        public Node(int value) {
            this.value = value;
        }
    }


    public static void main(String[] args){
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        Node n = zuijingongongzhuxian(root,
                root.left.left,
                root.right.right);
        System.out.println(n.value);
    }

    private static Node zuijingongongzhuxian(Node root, Node p, Node q) {
        if(root == null){
            return null;
        }
        if(root == p || root ==q){
            return root;
        }
        Node left = zuijingongongzhuxian(root.left,p ,q);
        Node right = zuijingongongzhuxian(root.right,p ,q);
        if(left != null && right != null){
            return root;
        }
        if(left != null){
            return left;
        }
        if(right != null){
            return right;
        }
        return null;
    }


    private static void print(Node root) {
        if(root == null) return;
        System.out.println(root.value);
        print(root.left);
        print(root.right);
    }

}